/********************************************
 * 顺序栈逻辑实现
 * Created by zlj on 2024/6/26.
********************************************/
#include "SeqStack.h"

/**
 * 初始化栈
 * @param s
 */
void InitSeqStack(SeqStack *s)
{
    //申请数据空间
    s->base = SEQ_STACK_LEN;
    assert(s->base != NULL);
    //设置容量的初始化大小
    s->capacity = STACK_INIT_SIZE;
    //设置栈的初始化指向
    s->top = 0;
}

/**
 * 增加栈的容量空间
 * @param s
 * @return
 */
bool SeqStack_Inc(SeqStack *s)
{
    //在原来栈空间基础 上扩展
    ElemType *newBase = (ElemType *) realloc(s->base, sizeof(ElemType) * (s->capacity + STACK_INC_SIZE));
    //如果扩展失败，提示失败并退出
    if (newBase == NULL)
    {
        printf("Not Enough Memory,Unable to apply for space . \n");
        return FALSE;
    }
    //将栈的基址指向扩展后的空间
    s->base = newBase;
    //将栈现容量设置为原栈容量+扩展的容量
    s->capacity += STACK_INC_SIZE;
    return TRUE;
}

/**
 * 判断是否栈已满
 * @param s
 * @return
 */
bool SeqStack_IsFull(SeqStack *s)
{
    return s->top == s->capacity;
}

/**
 * 判断栈空
 * @param s
 * @return
 */
bool SeqStack_IsEmpty(SeqStack *s)
{
    return s->top == 0;
}

/**
 * 入栈
 * @param s
 * @param x
 */
void SeqStack_Push(SeqStack *s, ElemType x)
{
    //判断栈是否已满,如果不是真正意义上的满（还可以连接申请空间）则申请空间
    if (SeqStack_IsFull(s) && !SeqStack_Inc(s))
    {
        printf("Stack space is full, unable to apply for space. \n");
        return;
    }
    //栈未满，数据入栈（数据先栈，top+1)
    s->base[s->top++] = x;
}

/**
 * 出栈
 * @param s
 */
void SeqStack_Pop(SeqStack *s)
{
    if (SeqStack_IsEmpty(s))
    {
        printf("The stack space is empty and cannot retrieve the top element of the stack. \n");
        return;
    }
    s->top--;
}

/**
 * 获取栈顶元素
 * @param s
 * @param v
 * @return
 */
bool SeqStack_GetTop(SeqStack *s, ElemType *v)
{
    //如果栈为空，则获取不了栈顶元素
    if (SeqStack_IsEmpty(s))
    {
        printf("The stack space is empty and cannot retrieve the top element of the stack. \n");
        return FALSE;
    }
    //获取栈顶元素，top-1为栈顶元素所在栈的位置
    *v = s->base[s->top - 1];
    return TRUE;
}

/**
 * 打印
 * @param s
 */
void SeqStack_Show(SeqStack *s)
{
    for (int i = s->top - 1; i >= 0; --i)
    {
        printf("%d ", s->base[i]);
    }
    printf("\n");
}

/**
 * 元素个数
 * @param s
 * @return
 */
int SeqStack_Length(SeqStack *s)
{
    return s->top;
}

/**
 * 清空栈
 * @param s
 */
void SeqStack_Clear(SeqStack *s)
{
    s->top = 0;
}

/**
 * 销毁
 * @param s
 */
void SeqStack_Destory(SeqStack *s)
{
    free(s->base);
    s->base = NULL;
    s->capacity = s->top = 0;
}

